import React, { useEffect, useState } from 'react'
import axios from '../../../api/http'  
function Index() {
  const [list,setlist]=useState<any[]>([])
  useEffect(()=>{
    axios.get('/book/list').then(res=>{
      // 兼容两种返回结构：{code,data} 或直接数组
      const data = Array.isArray(res) ? res : (res.data || [])
      setlist(data)
    })
  },[])

  const renderImages = (url:string) => {
    // 后端只给一个图片时，按单图展示；如果是以逗号分隔的多图，拆分
    const imgs = typeof url === 'string' ? url.split(',') : []
    const isMulti = imgs.length > 1
    return (
      <div style={{display:'grid',gridTemplateColumns:isMulti? 'repeat(3,1fr)':'1fr',gap:'6px',marginTop:'8px'}}>
        {imgs.map((src,idx)=> (
          <img key={idx} src={src.trim()} alt="pic" style={{width:'100%',height:isMulti?90:180,objectFit:'cover',borderRadius:'6px'}}/>
        ))}
      </div>
    )
  }

  return (
    <div style={{background:'#fff'}}>
      {list.map((item:any,idx:number)=> (
        <div key={item.textid || idx} style={{padding:'12px',borderBottom:'8px solid #f5f5f5'}}>
          {/* 头部：头像+昵称+身份 */}
          <div style={{display:'flex',alignItems:'center',gap:'10px'}}>
            <img src={item.doctorimage || 'https://via.placeholder.com/40'} alt="avatar" style={{width:40,height:40,borderRadius:'50%'}}/>
            <div>
              <div style={{fontWeight:600}}>{item.doctorname || '匿名用户'}</div>
              <div style={{fontSize:12,color:'#9e9e9e'}}>{item.doctorstate || '亲身经历的人'}</div>
            </div>
          </div>

          {/* 标题 */}
          <div style={{fontSize:18,fontWeight:700,marginTop:'10px',lineHeight:1.4}}>
            {item.texttitle}
          </div>

          {/* 图片 */}
          {item.textimage ? renderImages(item.textimage) : null}

          {/* 描述 */}
          <div style={{color:'#666',marginTop:'10px',lineHeight:1.6}}>
            {(item.textdescword || '').slice(0,80)}...
          </div>

          {/* 底部操作 */}
          <div style={{display:'flex',alignItems:'center',gap:'14px',marginTop:'10px',color:'#9e9e9e',fontSize:12}}>
            <span>📁 案例</span>
            <span>💬 7</span>
            <span>👍 {item.doctorgood || '95'}</span>
          </div>
        </div>
      ))}
    </div>
  )
}

export default Index
